package timing.ukulele.flow.extention;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import timing.ukulele.cache.redis.RedisCache;
import org.activiti.engine.impl.persistence.deploy.DeploymentCache;
import org.activiti.engine.impl.persistence.deploy.ProcessDefinitionCacheEntry;
import org.springframework.util.StringUtils;

/**
 * 存在序列化反序列化相关的问题 TODO
 */
public class DistributedCache implements DeploymentCache<ProcessDefinitionCacheEntry> {

    private final RedisCache redisCache;

    public DistributedCache(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @Override
    public ProcessDefinitionCacheEntry get(String id) {
        final Object object = redisCache.get(ActiviciConstant.CACHE_PREFIX_PROCESS + id);
        if (object != null) {
            String json = (String) object;
            ObjectMapper mapper = new ObjectMapper();
            ProcessDefinitionCacheEntry entity = null;
            try {
                entity = mapper.readValue(json, ProcessDefinitionCacheEntry.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return entity;
        }
        return null;
    }

    @Override
    public boolean contains(String s) {
        redisCache.contains(ActiviciConstant.CACHE_PREFIX_PROCESS + s);
        return false;
    }

    @Override
    public void add(String id, ProcessDefinitionCacheEntry processDefinitionEntity) {
        if (StringUtils.isEmpty(id))
            return;
        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(processDefinitionEntity);
            redisCache.put(ActiviciConstant.CACHE_PREFIX_PROCESS + id, json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void remove(String id) {
        if (StringUtils.isEmpty(id))
            return;
        if (contains(id))
            redisCache.remove(ActiviciConstant.CACHE_PREFIX_PROCESS + id);
    }

    @Override
    public void clear() {
        redisCache.clear();
    }
}
